package stackqueue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/8 13:47
 */
public class RemoveDuplicates {

    /**
     * 栈
     * @param s
     * @return
     */
    public String removeDuplicates(String s) {
        StringBuilder result = new StringBuilder();
        int index = -1;
        for (int i = 0; i < s.length(); i++) {
            //当栈为空或当前元素与栈顶元素相等
            if (index ==-1 || s.charAt(i) != result.charAt(index)) {
                result.append(s.charAt(i));
                index++;
            } else {
                result.deleteCharAt(index);
                index--;
            }
        }
        return result.toString();
    }

    /**
     * 双指针做法
     * @param s
     * @return
     */
    public String removeDuplicates1(String s) {
        char[] chars = s.toCharArray();
        int slow = 0;
        for (int fast = 0; fast < s.length(); fast++) {
            chars[slow] = chars[fast];
            if (slow == 0 || chars[slow] != chars[slow - 1]) {
                slow++;
            } else {
                //此时chars[slow] = chars[slow - 1]
                slow--;
            }
        }
        //String(c, offset, count)
        return new String(chars, 0, slow);
    }

    public static void main(String[] args) {

    }
}
